import React, { useState } from 'react';
import { List, Button, Space, Tooltip, Menu, Dropdown, Tag, Modal } from 'antd';
import {
  EditOutlined,
  DeleteOutlined,
  CopyOutlined,
  DatabaseOutlined,
  FolderOpenOutlined,
  MoreOutlined,
  LinkOutlined,
} from '@ant-design/icons';
import { ConnectionInfo, ConnectionGroup } from '@shared/types';
import { useConnectionsStore, formatLastConnected, getStatusColor, getOsIcon } from '@renderer/stores/connectionsStore';
import { useTerminalStore } from '@renderer/stores/terminalStore';
import { ConnectionEditModal } from './ConnectionEditModal';
import { message, notification } from 'antd';
import { useNavigate } from 'react-router-dom';

interface ConnectionListProps {
  connections: ConnectionInfo[];
}

interface GroupedConnections {
  group: ConnectionGroup | null;
  connections: ConnectionInfo[];
}

export const ConnectionListComponent: React.FC<ConnectionListProps> = ({ connections }) => {
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [editConnectionId, setEditConnectionId] = useState<string | null>(null);
  const [connecting, setConnecting] = useState(false);

  const navigate = useNavigate();

  const {
    deleteConnection,
    groups,
    updateConnectionStatus,
    addActiveConnector,
    removeActiveConnector,
    connectionAuths,
  } = useConnectionsStore();
  const { createSession, getSessionsByConnection } = useTerminalStore();

  // 处理连接按钮 - 实际执行SSH连接并打开终端
  const handleConnect = async (connection: ConnectionInfo) => {
    try {
      setConnecting(true);

      // 更新状态为连接中
      updateConnectionStatus(connection.id, 'connecting');

      // 获取认证信息
      const auth = connectionAuths.find(a => a.connectionId === connection.id);
      if (!auth) {
        Modal.error({
          title: '认证信息缺失',
          content: '请先为该连接配置认证信息（密码或密钥）',
        });
        updateConnectionStatus(connection.id, 'error');
        return;
      }

      // 调用SSH连接（通过IPC）
      // FIXME: 需要先完善preload中的API声明
      // const result = await window.electronAPI?.ssh.connect(connection, auth);
      // if (!result?.success) {
      //   throw new Error(result?.error || '连接失败');
      // }

      // 模拟SSH连接过程
      await new Promise((resolve, reject) => {
        setTimeout(() => {
          // 模拟连接结果
          const success = Math.random() > 0.2; // 80%成功率
          if (success) {
            resolve(true);
          } else {
            reject(new Error('连接超时：请检查网络连接或服务器配置'));
          }
        }, 2000);
      });

      // 连接成功
      updateConnectionStatus(connection.id, 'connected', 'linux');

      // 创建终端会话
      const session = createSession(connection);

      notification.success({
        message: '连接成功',
        description: `已连接到 ${connection.name}`,
        placement: 'bottomRight',
      });

      // 跳转到终端页面
      navigate('/terminal');

      setConnecting(false);
    } catch (error: any) {
      updateConnectionStatus(connection.id, 'error');
      setConnecting(false);

      Modal.error({
        title: '连接失败',
        content: error.message || 'SSH连接失败，请检查配置',
      });
    }
  };

  // 处理断开连接
  const handleDisconnect = (connection: ConnectionInfo) => {
    // 断开SSH连接
    // window.electronAPI?.ssh.disconnect(connection.id);

    const sessions = getSessionsByConnection(connection.id);
    sessions.forEach(session => {
      // 关闭相关终端会话
      // window.electronAPI?.ssh.disconnect(connection.id);
    });

    // 模拟断开连接
    if (connection.status === 'connected') {
      updateConnectionStatus(connection.id, 'disconnected');
      message.info(`已断开连接 ${connection.name}`);
    }
  };

  // 处理编辑连接
  const handleEdit = (connectionId: string) => {
    setEditConnectionId(connectionId);
    setEditModalVisible(true);
  };

  // 处理删除连接
  const handleDelete = (connectionId: string, connectionName: string) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除连接"${connectionName}"吗？`,
      okText: '删除',
      cancelText: '取消',
      okButtonProps: { danger: true },
      onOk: () => {
        deleteConnection(connectionId);
        message.success('连接已删除');
      },
    });
  };

  // 处理复制连接信息
  const handleCopyInfo = (connection: ConnectionInfo) => {
    const info = `${connection.host}:${connection.port} ${connection.username}`;
    navigator.clipboard.writeText(info).then(() => {
      message.success('已复制到剪贴板');
    });
  };

  // 创建右键菜单
  const getContextMenu = (connection: ConnectionInfo) => (
    <Menu>
      <Menu.Item
        key="connect"
        icon={<LinkOutlined />}
        onClick={() => handleConnect(connection)}
      >
        {connection.status === 'connected' ? '断开连接' : '连接'}
      </Menu.Item>
      <Menu.Item
        key="edit"
        icon={<EditOutlined />}
        onClick={() => handleEdit(connection.id)}
      >
        编辑
      </Menu.Item>
      <Menu.Item
        key="copy"
        icon={<CopyOutlined />}
        onClick={() => handleCopyInfo(connection)}
      >
        复制信息
      </Menu.Item>
      <Menu.Divider />
      <Menu.Item
        key="delete"
        icon={<DeleteOutlined />}
        danger
        onClick={() => handleDelete(connection.id, connection.name)}
      >
        删除
      </Menu.Item>
    </Menu>
  );

  // 按分组组织连接
  const groupConnections = (): GroupedConnections[] => {
    const result: GroupedConnections[] = [];

    // 按分组组织
    const connectionsByGroup = new Map<string | null, ConnectionInfo[]>();

    connections.forEach((conn) => {
      const groupId = conn.groupId || null;
      if (!connectionsByGroup.has(groupId)) {
        connectionsByGroup.set(groupId, []);
      }
      connectionsByGroup.get(groupId)!.push(conn);
    });

    // 转换格式
    connectionsByGroup.forEach((conns, groupId) => {
      const group = groupId ? groups.find((g) => g.id === groupId) || null : null;
      result.push({ group, connections: conns });
    });

    // 按排序顺序排列
    result.sort((a, b) => {
      if (!a.group) return -1;
      if (!b.group) return 1;
      return a.group.order - b.group.order;
    });

    return result;
  };

  // 获取分组名称
  const getGroupName = (group: ConnectionGroup | null): string => {
    return group?.name || '未分组';
  };

  // 渲染连接项
  const renderConnectionItem = (connection: ConnectionInfo) => {
    const isConnected = connection.status === 'connected';

    return (
      <div className="connection-item">
        <div className="connection-item-main">
          <div className="connection-item-header">
            <div className="connection-item-title">
              <span className="connection-item-icon">{getOsIcon(connection.osType)}</span>
              <span className="connection-item-name">{connection.name}</span>
              <span
                className="connection-item-status"
                style={{ backgroundColor: getStatusColor(connection.status) }}
              />
            </div>
            <Space size="small">
              {isConnected ? (
                <Button
                  size="small"
                  onClick={() => handleDisconnect(connection)}
                >
                  断开
                </Button>
              ) : (
                <Button
                  type="primary"
                  size="small"
                  onClick={() => handleConnect(connection)}
                  loading={connecting}
                >
                  连接
                </Button>
              )}
              <Button
                size="small"
                icon={<EditOutlined />}
                onClick={() => handleEdit(connection.id)}
              />
              <Dropdown overlay={getContextMenu(connection)} trigger={['click']}>
                <Button
                  size="small"
                  icon={<MoreOutlined />}
                />
              </Dropdown>
            </Space>
          </div>

          <div className="connection-item-body">
            <div className="connection-item-detail">
              <span className="connection-item-label">地址:</span>
              <span className="connection-item-value">{connection.host}:{connection.port}</span>
            </div>
            <div className="connection-item-detail">
              <span className="connection-item-label">用户:</span>
              <span className="connection-item-value">{connection.username}</span>
            </div>
            {connection.osType && (
              <div className="connection-item-detail">
                <span className="connection-item-label">系统:</span>
                <span className="connection-item-value">
                  {connection.osType === 'linux' ? 'Linux' : connection.osType === 'windows' ? 'Windows' : 'macOS'}
                </span>
              </div>
            )}
            {connection.lastConnected && (
              <div className="connection-item-detail">
                <span className="connection-item-label">最后连接:</span>
                <span className="connection-item-value">{formatLastConnected(connection.lastConnected)}</span>
              </div>
            )}
          </div>

          {connection.tags && connection.tags.length > 0 && (
            <div className="connection-item-tags">
              {connection.tags.map((tag) => (
                <Tag key={tag} color="blue" size="small">
                  {tag}
                </Tag>
              ))}
            </div>
          )}
        </div>
      </div>
    );
  };

  const grouped = groupConnections();

  return (
    <>
      <div className="connection-list">
        {grouped.length === 0 ? (
          <div className="connection-empty">
            <DatabaseOutlined style={{ fontSize: 48, color: '#d9d9d9' }} />
            <h3>暂无连接</h3>
            <p>点击上方"新建连接"按钮创建您的第一个SSH连接</p>
          </div>
        ) : (
          grouped.map(({ group, connections }) => (
            <div key={group?.id || 'ungrouped'} className="connection-group">
              <div className="connection-group-header">
                {group ? (
                  <>
                    <FolderOpenOutlined style={{ color: group.color || '#1890ff' }} />
                    <span className="connection-group-name">
                      {group.name}
                    </span>
                    <span className="connection-group-count">({connections.length})</span>
                  </>
                ) : (
                  <>
                    <FolderOpenOutlined />
                    <span className="connection-group-name">未分组</span>
                    <span className="connection-group-count">({connections.length})</span>
                  </>
                )}
              </div>
              <div className="connection-group-items">
                <List
                  dataSource={connections}
                  renderItem={(connection) => (
                    <List.Item key={connection.id} className="connection-list-item">
                      {renderConnectionItem(connection)}
                    </List.Item>
                  )}
                />
              </div>
            </div>
          ))
        )}
      </div>

      <ConnectionEditModal
        visible={editModalVisible}
        onClose={() => setEditModalVisible(false)}
        connectionId={editConnectionId || undefined}
      />
    </>
  );
};